<?php

require_once(dirname(__FILE__) . '/appconf.php');

class Email_exp extends Site {

    function setup() {
        $this->run_modes('export', 'email_points');
        $this->start_mode('export');
        $this->selfurl = '/test.php';
        parent::setup();
    }

    function cgiapp_prerun($rm='') {
        //$this->Member = getModel('Model_Member');
        $this->Points = getModel('Model_Points');
        parent::cgiapp_prerun();
    }

    function action_export() {
        $issue = date("YmdHis");
        $mem_arr = db_query_hash("member_imore", array("field" => "id,username,email", "where" => "status=1 and email_status=1 and email_receive=1"));
        $out = "";
        if (!empty($mem_arr['result'])) {
            foreach ($mem_arr['result'] as $k => $v) {
                $out .= $v["id"] . "," . $v["username"] . "," . $v["email"] . ",".$issue."\n";
            }
        }
        $out = "Email,Username,Id,Issue\n" . $out;
        $this->data_export($out);
    }

    function action_email_points() {
        $uid = intval($this->get_q('uid', 0, 'int'));
        $issue = intval($this->get_q('issue', 0, 'int'));
        /* * *
          $username = $this->get_q('username', '');
          $user = array();
          if (!empty($username)) {
          $user = $this->Member->getMember(0, '', $username);
          }
          $uid = isset($user['result'][0]['id']) ? intval($user['result'][0]['id']) : 0;
         * * */
        if (!empty($uid)) {
            $sum = db_query_count("edm", "uid=" . mysql_escape_string($uid) . " and issue='" . mysql_escape_string($issue)."'");
            if ($sum < 1) {
                $a = $this->Points->points_record($uid, "open_edm", str_replace("[edm名稱]", $issue, OPEN_EDM_LANG));
                if (intval($a['ret']) == 1)
                    db_add("edm", array("uid" => $uid, "issue" => $issue));
            }
        }
    }

    function data_export($body, $filename="") {
        if (empty($filename)) {
            $filename = time();
        }
        header("Content-type:application/vnd.ms-csv;charset=utf8");
        header("Content-Disposition:filename=" . $filename . ".csv");
        echo "\xEF\xBB\xBF" . $body;
        exit;
    }

}

$webapp = new Email_exp();
$webapp->run();
?>